package com.fjh.roadmannage.base

import com.cxz.kotlin.baselibs.http.HttpStatus
import com.cxz.kotlin.baselibs.http.exception.ExceptionHandle
import com.cxz.kotlin.baselibs.mvp.BasePresenter
import com.cxz.kotlin.baselibs.mvp.IView
import com.cxz.kotlin.baselibs.rx.SchedulerUtils
import com.fjh.roadmannage.bean.HttpResult
import io.reactivex.rxjava3.core.Observable

open class Presenter<V : IView> : BasePresenter<V>() {

    protected fun <D> use(
        request: () -> Observable<HttpResult<D>>,
        sucess: (d: D?) -> Unit
    ) {
        addDisposable(
            request()
                .compose(SchedulerUtils.ioToMain())
                ?.subscribe({

                    mView?.hideLoading()
                    when (it.status) {
                        HttpStatus.SUCCESS -> sucess(it.data)
                        HttpStatus.TOKEN_INVALID -> {
                            // Token 过期，重新登录
                            mView?.errorToken()
                        }
                        else -> mView?.showError(it.message)
                    }
                }, {
                    mView?.hideLoading()
                    mView?.showDefaultMsg(ExceptionHandle.handleException(it))
                })
        )
    }

}